package com.judian.smart.decoration;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
    private int spanCount; //列数
    private int spacing; //间隔
    private int orientation = LinearLayoutManager.VERTICAL;//布局方向 默认竖向布局
    /**
     * 是否包含边缘<br/>
     * true -> 包含 = 表示列表周围也需要间隔<br/>
     * false -> 不包含 = 表示列表周围不需要间隔，即只有item之间有间隔
     */
    private boolean includeEdge;

    /**
     * 给GridLayoutManager类型的RecyclerView创建一个间隔
     *
     * @param spanCount   列数
     * @param spacing     间隔
     * @param includeEdge 是否包含边缘
     */
    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int column = position % spanCount;

        //判断布局方向
        if (orientation == LinearLayoutManager.VERTICAL) {
            if (includeEdge) {//如果包含边缘，则计算0列和最大列数的左间距和右间距
                outRect.left = spacing - column * spacing / spanCount;
                outRect.right = (column + 1) * spacing / spanCount;
                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount;
                outRect.right = spacing - (column + 1) * spacing / spanCount;
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }
}
